package com.jiang.demo.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * ---------------------------------------------------------------------------------------------------------------
 * - 2024-06-01 15:24 - jiangshaoneng -
 * ---------------------------------------------------------------------------------------------------------------
 * -      ██╗██╗ █████╗ ███╗   ██╗ ██████╗ ███████╗██╗  ██╗ █████╗  ██████╗ ███╗   ██╗███████╗███╗   ██╗ ██████╗
 * -      ██║██║██╔══██╗████╗  ██║██╔════╝ ██╔════╝██║  ██║██╔══██╗██╔═══██╗████╗  ██║██╔════╝████╗  ██║██╔════╝
 * -      ██║██║███████║██╔██╗ ██║██║  ███╗███████╗███████║███████║██║   ██║██╔██╗ ██║█████╗  ██╔██╗ ██║██║  ███╗
 * - ██   ██║██║██╔══██║██║╚██╗██║██║   ██║╚════██║██╔══██║██╔══██║██║   ██║██║╚██╗██║██╔══╝  ██║╚██╗██║██║   ██║
 * - ╚█████╔╝██║██║  ██║██║ ╚████║╚██████╔╝███████║██║  ██║██║  ██║╚██████╔╝██║ ╚████║███████╗██║ ╚████║╚██████╔╝
 * -  ╚════╝ ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝╚══════╝╚═╝  ╚═══╝ ╚═════╝
 * ---------------------------------------------------------------------------------------------------------------
 * ---------------------------------------------------------------------------------------------------------------
 */
public class JsonParseUtil {

    /**
     * 获取json深层字段信息
     * @param jsonObject {"took":3043,"timed_out":false,"_shards":{"total":7,"successful":7,"skipped":0,"failed":0},"hits":{"total":{"value":38,"relation":"eq"},"max_score":null,"hits":[]},"aggregations":{"3":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[{"key":"error_entry","doc_count":34},{"key":"error_patch","doc_count":4}]}}}
     * @param jsonPath aggregations.3.buckets.[key=error_entry].doc_count
     */
    public static Object getDeepFieldValue(JSONObject jsonObject, String jsonPath) {
        String[] split = jsonPath.split("\\.");
        Object currentObject = jsonObject;

        for (String item : split) {
            if (currentObject instanceof JSONObject) { // 判断为JSONObject
                JSONObject temp = (JSONObject) currentObject;
                if (!temp.containsKey(item)) {
                    return null;
                }
                currentObject = temp.get(item);

            } else if (currentObject instanceof JSONArray) { // 判断为JSONArray
                JSONArray temps = (JSONArray) currentObject;
                String replace = item.replace("[", "").replace("]", "");
                if(replace.contains("=")){
                    String[] kv = item.replace("[", "").replace("]", "").split("=");
                    boolean exist = false;
                    for (Object obj : temps) {
                        if (!(obj instanceof JSONObject)) {
                            continue;
                        }
                        JSONObject json = (JSONObject) obj;
                        if (kv.length == 2 && json.containsKey(kv[0]) && String.valueOf(json.get(kv[0])).equals(kv[1])) {
                            currentObject = json;
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) return null;
                }else {
                    try {
                        int index = Integer.parseInt(replace);
                        currentObject = temps.get(index);
                        continue;
                    }catch (Exception ignore) {}
                    return null;
                }
            } else {
                return null;
            }
        }
        return currentObject;
    }

    public static void main(String[] args) {

        JSONObject jsonObject = JSONObject.parseObject("{\"dataJson\":[{\"AwardConfig\":[{\"awardId\":\"10010\",\"rowNum\":3,\"awardNum\":0,\"awardName\":\"dsfd\",\"day\":1,\"awardType\":[\"333\"]},{\"awardId\":\"10011\",\"rowNum\":4,\"awardNum\":0,\"awardName\":\"asd\",\"day\":2,\"awardType\":[\"333\"]},{\"awardId\":\"10011\",\"rowNum\":5,\"awardNum\":0,\"awardName\":\"xcv\",\"day\":3,\"awardType\":[\"333\"]},{\"awardId\":\"10011\",\"rowNum\":6,\"awardNum\":0,\"awardName\":\"zxcv\",\"day\":4,\"awardType\":[\"333\"]},{\"awardId\":\"10011\",\"rowNum\":7,\"awardNum\":0,\"awardName\":\"sdfa\",\"day\":5,\"awardType\":[\"555\"]},{\"awardId\":\"10011\",\"rowNum\":8,\"awardNum\":0,\"awardName\":\"dfsas\",\"day\":6,\"awardType\":[\"111\"]},{\"awardId\":\"10011\",\"rowNum\":9,\"awardNum\":0,\"awardName\":\"zxcv\",\"day\":7,\"awardType\":[\"222\"]}],\"BaseConfig\":[{\"activityBackgroundImg\":[\"https://xxxxxxx.jpg\"],\"rowNum\":3,\"resetClock\":0}]}],\"extDataJson\":{\"activityNo\":\"10001\",\"tab1\":\"1\",\"tab2\":\"1\",\"tabName\":\"sdagas\"}}");
        Object deepFieldValue1 = getDeepFieldValue(jsonObject, "extDataJson.activityNo");
        System.out.println(deepFieldValue1);

        Object deepFieldValue2 = getDeepFieldValue(jsonObject, "dataJson.[0].BaseConfig.[0].activityBackgroundImg");
        System.out.println(deepFieldValue2);

        Object deepFieldValue3 = getDeepFieldValue(jsonObject, "dataJson.[0].BaseConfig.[0].activityBackgroundImg.[0]");
        System.out.println(deepFieldValue3);

        Object deepFieldValue4 = getDeepFieldValue(jsonObject, "dataJson.[0].AwardConfig.[awardId=10010]");
        System.out.println(deepFieldValue4);
    }
}
